<template>
  <a-radio-group v-model:value="selectedOption">
    <a-radio v-for="(item, index) in effectItems" :value="item[valuePropName]" :key="item[valuePropName]">{{item[labelPropName]}}</a-radio>
  </a-radio-group>
</template>
<script>

/**
 * 进一步封装Antdv的Radio组件，简化代码量
 */
export default {
  inheritAttrs: false,
  name: 'SagRadio',
  inject: ['getDictByType'], // 依赖全局provide的
  props: {
    datasource: { type: [Array, String, Function], default: null },
    labelPropName: { type: [String, Number], default: 'label' },
    valuePropName: { type: [String, Number], default: 'value' },
    value: { type: [String, Number], default: null },
    includeDisabled: { type: Boolean, default: false },
    numberValue: { type: Boolean, default: false },
  },
  emits: ['update:value'],
  data() {
    return {
      items: [],
      selectedOption: this.value,
    };
  },
  computed: {
    effectItems() {
      const { valuePropName, items } = this;
      if(this.numberValue){
        items.forEach(item => item[valuePropName] = Number(item[valuePropName]))
      }
      return items;
    },
  },
  watch: {
    datasource: {
      immediate: true,
      handler(val, old) {

        if (Array.isArray(val)) {
          this.items.splice(0, this.items.length, ...val);
        } else if (typeof val === 'string' && val.length > 0) {
          this.items.splice(0, this.items.length);
          this.loadDictData();
        } else if (val instanceof Function) {
          this.items.splice(0, this.items.length);
          val()
              .then(resp => {
                if (resp.success && resp.data && resp.data.length > 0) {
                  this.items.push(...resp.data);
                }
              })
              .catch(() => {
                console.warn('没有获得数据源数据:' + this.datasource);
              });
        }
      },
    },
    value: {
      immediate: true,
      handler(val) {
        this.selectedOption = val;
      },
    },
    selectedOption: {
      immediate: true,
      handler(val) {
        this.$emit('update:value', val);
      },
    },
  },
  methods: {
    loadDictData() {
      // 加载数据字典数据
      this.getDictByType(this.datasource, this.includeDisabled ? 1 : 0).then(resp => {
        if (resp && resp.success && resp.data && resp.data.length > 0) {
          const options = resp.data.map(x => ({
            [this.labelPropName]: x[1],
            [this.valuePropName]: x[0],
          }));
          this.items.push(...options);
          this.$nextTick(() => {
            this.selectedOption = this.value;
          });
        } else {
          console.warn('没有获取到数据源数据:' + this.datasource);
        }
      });
    },
  },
};
</script>
